
package pl.genapp.stocksense;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.TimeChart;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pl.genapp.appsense.R;
import pl.genapp.stocksense.libraries.HistoricalDataProvider;
import pl.genapp.stocksense.libraries.HttpMakerAsyncTask;
import pl.genapp.stocksense.libraries.JSONStringMaker;
import pl.genapp.stocksense.libraries.SentGraph;
import pl.genapp.stocksense.libraries.SentGraph.OnSentClickListener;
import pl.genapp.stocksense.libraries.SentGraphArrow;
import pl.genapp.stocksense.libraries.SentGraphCircles;
import pl.genapp.stocksense.libraries.SentGraphPie;
import pl.genapp.stocksense.others.PostExecuteReaction;
import pl.genapp.stocksense.others.StockSenseState;
import pl.genapp.stocksense.others.TimeChartHelper;
import pl.genapp.stocksense.others.TimeLineClickListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import bin.classes.com.viewpagerindicator.UnderlinePageIndicator;

/**
 * TODO: synchronizacja watkow
 * 
 * @author dominik
 * 
 */
public class EntityScreenFragment extends Fragment {
	
	private String entityName;
	
	private ViewPager pager;
	private ViewGroup layoutView;
	private AwesomePagerAdapter adapter;
	
	private EntityScreenHome screenOne;
	private EntityScreenHomeTopic screenFour;
	private EntityScreenFinancial screenTwo;
	private EntityScreenSentGraphs screenThree;
	
	/* Sentiments data for charts */
	private ArrayList[] sentimentsChartsData = { new ArrayList<Double>(), new ArrayList<Double>(), new ArrayList<Double>(), new ArrayList<Double>(), new ArrayList<Double>(), new ArrayList<Double>() };
	private boolean sentimentsChartsDataValid = false;
	
	/* Top three news */
	private String[][] topThreeNewsData;
	private boolean topThreeNewsDataValid = true;
	
	/* Financial data */
	private List<HistoricalDataProvider.HistoricalDataField> financialChartsData;
	private boolean financialChartsDataValid = false;
	
	public static EntityScreenFragment newInstance(String entityName) {
		
		EntityScreenFragment fragment = new EntityScreenFragment();
		
		Bundle arg = new Bundle();
		arg.putString("entityname", entityName);
		
		fragment.setArguments(arg);
		
		return fragment;
		
	}
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		entityName = getArguments().getString("entityname");
		
		if (screenOne == null) screenOne = new EntityScreenHome(this);
		if (screenTwo == null) screenTwo = new EntityScreenFinancial(this);
		if (screenThree == null) screenThree = new EntityScreenSentGraphs(this);
		if (screenFour == null) screenFour = new EntityScreenHomeTopic(this);
		
		Log.d("stocksense", "entity fragment - on create");
		
	}

	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		layoutView = (ViewGroup) inflater.inflate(R.layout.fragment_entity_screen, container, false);
		adapter = new AwesomePagerAdapter();
		
		pager = (ViewPager) layoutView.findViewById(R.id.entityViewPager);
		pager.setAdapter(adapter);
		
		UnderlinePageIndicator indicator = (UnderlinePageIndicator) layoutView.findViewById(R.id.pageIndicator);
		indicator.setViewPager(pager);
		indicator.setFades(false);
		indicator.setCurrentItem(1);
		
		indicator.setOnPageChangeListener(new OnPageChangeListener() {
			
			public void onPageSelected(int nr) {
				// Log.d("stocksense", "On page selected " + nr);
				updateDataDependsOnCurrentPage(nr);
			}
			
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// Log.d("stocksense", "On page scrolled " + arg0 + " " + arg1 +
				// " " + arg2);
				
				if (pager.getCurrentItem() == 0 && arg1 >= 0.01f) screenThree.clearGraphs();
				
			}
			
			public void onPageScrollStateChanged(int state) {
				// Log.d("stocksense", "On page state changed " + state);
				
				if (state == 0 && pager.getCurrentItem() == 0 && sentimentsChartsDataValid == true) screenThree.doGraphsThings();
			}
			
		});
		
		// register timeline listeners
		StackSense activity = (StackSense) getActivity();
		
		if (!activity.getTimelineListeners().contains(timelineClickListener)) {
			activity.getTimelineListeners().add(timelineClickListener);
		}
		
		return layoutView;
	}
	
	void updateDataDependsOnCurrentPage(int pageNo) {
		
		int selectedMonth = ((StockSenseState) getActivity().getApplication()).getSelectedMonths();
		
		switch (pageNo) {
		
			case 0:
				
				if (!sentimentsChartsDataValid) {
					loadSentimentsChartsData(selectedMonth);
				} // else
					// screenThree.doGraphsThings();
				
				break;
			
			case 1:
				break;
				
			case 2:
				break;
			
			case 3:
				
				if (!financialChartsDataValid) {
					loadFinancialChartData(selectedMonth);
				} else
					screenTwo.loadFinancialGraph();
				
				if (!sentimentsChartsDataValid) {
					loadSentimentsChartsData(selectedMonth);
				}
				
				break;
		
		}
		
	}
	
	public void onDestroy() {
		super.onDestroy();
		Log.d("stocksense", "entity fragment - on destroy");
	}
	
	public void onResume() {
		StackSense activity = (StackSense) getActivity();
		
		if (!activity.getTimelineListeners().contains(timelineClickListener)) {
			activity.getTimelineListeners().add(timelineClickListener);
		}
		
		int selectedMonth = ((StockSenseState) getActivity().getApplication()).getSelectedMonths();
		
		if(pager.getCurrentItem() == 0) 
			loadSentimentsChartsData(selectedMonth);
		
		super.onResume();
	}
	
	public void onPause() {
		super.onPause();
		((StackSense) getActivity()).getTimelineListeners().remove(timelineClickListener);
	}
	
	TimeLineClickListener timelineClickListener = new TimeLineClickListener() {
		
		public void click(int month) {
			
			loadTopThreeNewsData(month);
			
			switch (pager.getCurrentItem()) {
			
				case 0:
					loadSentimentsChartsData(month);
					financialChartsDataValid = false;
					break;
				
				case 1:
					financialChartsDataValid = false;
					sentimentsChartsDataValid = false;
					break;
				
				case 2:
					financialChartsDataValid = false;
					sentimentsChartsDataValid = false;
					break;
				
				case 3:
					loadFinancialChartData(month);
					loadSentimentsChartsData(month);
					break;
			
			}
			
		}
	};
	
	PostExecuteReaction<JSONObject> onGetSentimentReaction = new PostExecuteReaction<JSONObject>() {
		
		public void onSuccess(Context context, JSONObject object) {
			
			for (ArrayList list : sentimentsChartsData)
				list.clear();
			
			try {
				JSONArray dataArray = object.getJSONArray("data");
				
				for (int i = 0; i < dataArray.length(); i++) {
					
					JSONArray sentimentData = dataArray.getJSONArray(i);
					
					for (int k = 0; k < sentimentData.length(); k++) {
						sentimentsChartsData[i].add((Double) sentimentData.getDouble(k));
					}
					
				}
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
			
			if (pager.getCurrentItem() == 0) screenThree.doGraphsThings();
			sentimentsChartsDataValid = true;
			
		};
		
	};
	
	void loadSentimentsChartsData(int months) {
		
		Calendar rightNow = Calendar.getInstance();
		final Calendar startDate = Calendar.getInstance();
		startDate.add(Calendar.MONTH, (-1) * months);
		int days = (int) ((rightNow.getTimeInMillis() - startDate.getTimeInMillis()) / (24 * 60 * 60 * 1000));
		
		String params = JSONStringMaker.getSentiments(getActivity(), days, entityName);
		new HttpMakerAsyncTask(getActivity(), onGetSentimentReaction).execute(params);
		
	}
	
	void loadFinancialChartData(int months) {
		
		Calendar rightNow = Calendar.getInstance();
		
		final Calendar startDate = Calendar.getInstance();
		startDate.add(Calendar.MONTH, (-1) * months);
		
		HistoricalDataProvider provider = new HistoricalDataProvider(getActivity().getApplicationContext(), screenTwo.onGetFinancialChartData);
		provider.execute("http://ichart.finance.yahoo.com/table.csv?s=" + entityName + "&a=" + startDate.get(Calendar.MONTH) + "&b=" + startDate.get(Calendar.DAY_OF_MONTH) + "&c="
				+ startDate.get(Calendar.YEAR) + "&d=" + rightNow.get(Calendar.MONTH) + "&e=" + rightNow.get(Calendar.DAY_OF_MONTH) + "&f=" + rightNow.get(Calendar.YEAR) + "&g=d&ignore=.csv");
		
	}
	
	void loadTopThreeNewsData(int months) {
		
		Log.d("stocksense", "Laduje ten szajs");
		
		String params = JSONStringMaker.getTopThreeNewsForEachSentiment(getActivity());
		new HttpMakerAsyncTask(getActivity(), screenOne.topThreeNewsDataReaction).execute(params);
		
	}
	
	public ArrayList[] getSentimentsChartsData() {
		return sentimentsChartsData;
	}
	
	public boolean isSentimentsChartsDataValid() {
		return sentimentsChartsDataValid;
	}
	
	public ViewPager getPager() {
		return pager;
	}
	
	public String getEntityName() {
		return entityName;
	}
	
	public List<HistoricalDataProvider.HistoricalDataField> getFinancialChartsData() {
		return financialChartsData;
	}
	
	public void setFinancialChartsData(List<HistoricalDataProvider.HistoricalDataField> financialChartsData) {
		this.financialChartsData = financialChartsData;
	}
	
	public boolean isFinancialChartsDataValid() {
		return financialChartsDataValid;
	}
	
	public void setFinancialChartsDataValid(boolean financialChartsDataValid) {
		this.financialChartsDataValid = financialChartsDataValid;
	}
	
	/*********************************************************
	 * ViewPager adapter
	 ********************************************************/
	private class AwesomePagerAdapter extends PagerAdapter {
		
		@Override
		public int getCount() {
			return 4;
		}
		
		@Override
		public Object instantiateItem(View collection, int position) {
			
			View layout;
			
			if (position == 0)
				layout = screenThree.setupView();
			else if (position == 1)
				layout = screenOne.setupView();
			else if (position == 2)
				layout = screenFour.setupView();
			else 
				layout = screenTwo.setupView();
			
			((ViewPager) collection).addView(layout, 0);
			
			return layout;
		}
		
		@Override
		public void destroyItem(View collection, int position, Object view) {
			((ViewPager) collection).removeView((View) view);
		}
		
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == ((View) object);
		}
		
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	
		super.onActivityResult(requestCode, resultCode, data);
		
		Log.d("stocksense", "fragment ac result!");
	}
	
}
